package net.mikoo.seals.biz.service.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import net.mikoo.seals.biz.mapper.DevicesMapper;
import net.mikoo.seals.biz.mapper.DevicesModelMapper;
import net.mikoo.seals.biz.service.OTAService;
import net.mikoo.seals.model.Devices;
import net.mikoo.seals.model.DevicesModel;
import net.mikoo.seals.model.DevicesModelQuery;

@Service
public class OTAServiceImpl implements OTAService {

	
	@Autowired
	private DevicesMapper devicesMapper;
	
	@Autowired
	private DevicesModelMapper devicesModelMapper;
	
	
	@Override
	public DevicesModel checkUpdate(long deviceId) {
		
		Devices device = devicesMapper.selectInfoById(deviceId);
		if(device == null) {
			throw new IllegalStateException("devices is not exist");
		}
		DevicesModelQuery query = new DevicesModelQuery();
		query.setModel(device.getModel());
		List<DevicesModel> deviceModelList = devicesModelMapper.selectListByQuery(query);
		if(deviceModelList != null && !deviceModelList.isEmpty()) {
			int currentVersion = Integer.valueOf(device.getDevicesVerson().replaceAll("\\.", ""));
			DevicesModel model = null;
			for(DevicesModel devicesModel : deviceModelList) {
				if(devicesModel == null || StringUtils.isBlank(devicesModel.getVersion())) {
					continue;
				}
				
				int version = Integer.valueOf(devicesModel.getVersion().replaceAll("\\.", ""));
				if(version > currentVersion) {
					currentVersion = version;
					model = devicesModel;
				}
			}
			return model;
		}
		return null;
	}

	
	
	
}
